#include <stdio.h>
#include "stm32f10x_rcc.h"
#include "stm32f10x_usart.h"

void app_uart1_init(int baudRate)
{
	GPIO_InitTypeDef gpio_def;
	USART_InitTypeDef uart_def;
	NVIC_InitTypeDef nvic_it;
	
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA,ENABLE);
	/*gpio init*/
	gpio_def.GPIO_Pin = GPIO_Pin_9;		//USART1_TX PA9
 	gpio_def.GPIO_Mode = GPIO_Mode_AF_PP;
	gpio_def.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA,&gpio_def);
	
	gpio_def.GPIO_Pin = GPIO_Pin_10;   //USART1_RX 	PA10
	gpio_def.GPIO_Mode = GPIO_Mode_IN_FLOATING;
	GPIO_Init(GPIOA,&gpio_def);
	
	/*uart init*/
	uart_def.USART_BaudRate = baudRate;
	uart_def.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
	uart_def.USART_WordLength = USART_WordLength_8b;
	uart_def.USART_StopBits = USART_StopBits_1;
	uart_def.USART_Parity = USART_Parity_No;
	uart_def.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
	USART_Init(USART1,&uart_def);
	
	/*NVIC init*/
	nvic_it.NVIC_IRQChannel = USART1_IRQn;
	nvic_it.NVIC_IRQChannelCmd = ENABLE;
	nvic_it.NVIC_IRQChannelPreemptionPriority = 3;
	nvic_it.NVIC_IRQChannelSubPriority = 3;
	NVIC_Init(&nvic_it);
	
	/*Enbale USART1 interrupt*/
	USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);
	
	/*Enable USART1*/
	USART_Cmd(USART1,ENABLE);	
}

char recv_buf[512] = {0};
int receive_count = 0;
void USART1_IRQHandler(void)
{
	char rval = 0;
	if(USART_GetITStatus(USART1,USART_IT_RXNE) == SET){
		rval = USART_ReceiveData(USART1);
		recv_buf[receive_count++] = rval;
		if(rval == '\r'){
		
		}else if(rval == '\n'){
			printf("recive %d data :%s\r\n",receive_count-2,recv_buf);
			receive_count = 0;
		}
	}
}

